package com.shxy.rlzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxy.rlzy.entity.EmployeeInfo;
import com.shxy.rlzy.entity.Salary;
import com.shxy.rlzy.entity.SalaryItem;
import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.mapper.EmployeeInfoMapper;
import com.shxy.rlzy.mapper.SalaryItemMapper;
import com.shxy.rlzy.mapper.SalaryMapper;
import com.shxy.rlzy.mapper.UserMapper;
import com.shxy.rlzy.service.IEmployeeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: tanhao
 * @Description: 员工信息管理实现类
 * @DateTime: 9/28/2021 8:50 PM
 **/
@Service
public class EmployeeInfoService extends ServiceImpl<EmployeeInfoMapper, EmployeeInfo> implements IEmployeeInfoService {
    @Autowired
    private EmployeeInfoMapper employeeInfoMapper;
    @Autowired
    private SalaryMapper salaryMapper;
    @Autowired
    private SalaryItemMapper salaryItemMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean phoneExist(Long id, String phone) {
        // 查询id不同且手机号相同的员工数量
        QueryWrapper<EmployeeInfo> qw = new QueryWrapper<EmployeeInfo>().eq("phone", phone);
        if(id != null && id > 0) {
            qw.ne("id", id);
        }
        return this.count(qw) > 0;
    }

    @Override
    public boolean idCardExist(Long id, String idCard) {
        // 查询id不同且身份证相同的员工数量
        QueryWrapper<EmployeeInfo> qw = new QueryWrapper<EmployeeInfo>().eq("id_card", idCard);
        if(id != null && id > 0) {
            qw.ne("id", id);
        }
        return this.count(qw) > 0;
    }

    @Override
    public Long getIdByIdCard(String idCard) {
        return employeeInfoMapper.getIdByIdCard(idCard);
    }

    @Override
    public List<EmployeeInfo> listByIdCards(List<String> idCards) {
        QueryWrapper<EmployeeInfo> qw = new QueryWrapper<>();
        qw.in("id_card", idCards);
        return employeeInfoMapper.selectList(qw);
    }

    @Override
    public EmployeeInfo getByPhone(String phone) {
        QueryWrapper<EmployeeInfo> qw = new QueryWrapper<>();
        qw.eq("phone", phone);
        return employeeInfoMapper.selectOne(qw);
    }

    @Override
    public boolean delete(EmployeeInfo employee) {
        // 1、获取工资信息
        Salary salary = salaryMapper.selectOne(new QueryWrapper<Salary>().eq("employee_id", employee.getId()));
        if(salary != null) {
            // 2、删除工资记录
            salaryItemMapper.delete(new QueryWrapper<SalaryItem>().eq("salary_id", salary.getId()));
            // 3、删除工资信息
            salaryMapper.deleteById(salary.getId());
        }
        // 4、删除员工对应的用户信息
        //userMapper.delete(new QueryWrapper<User>().eq("phone", employee.getPhone()));
        // 5、删除员工
        return employeeInfoMapper.deleteById(employee.getId()) > 0;
    }
}
